package com.nacai.im;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.HashMap;
import java.util.Map;

import protoc.Sync;
import sdkv2.Sdkv2;

import static android.text.TextUtils.isEmpty;

public class ImSdkUtils {

    public static Context mContext;
    private static Map<Long, Long> groupOffsetMap = new HashMap<>();
    private static Long localOffset = 0l;

    private ImSdkUtils() {
    }

    public static void ImSdkInit(Context context) {
        mContext = context;
    }

    public static void imLogin(String configInfo, DeviceInfo deviceInfo, ImUserLoginInfo user) {
        //  Sdk.setIMLogSwitch(false);
        //   Sdk.setImProtocolIsTcp(true);
        // Sdk.setLogServerAddress("192.168.1.124:11989", user.getEosNo());

        // 防止 SDK 频繁获取配置信息，如果本地已缓存 config，则传递
        if (TextUtils.isEmpty(configInfo)) {
            Sdkv2.imSdkSetBufferedServerNodeInfo(configInfo);
        }

        Sdkv2.setImServerAddress("https://dev-api.gac.top/v1/api/q", 18882);
        Sdkv2.setImLocalDevinfo(deviceInfo.getImMei(), deviceInfo.getType());
        Sdkv2.setImUserNo(user.getEosNo(), user.getPwd(), user.getImUid());

        new Thread(new Runnable() {
            @Override
            public void run() {
                Sdkv2.imSdkStartup();//sdk开始连接
                Sdkv2.imLogin();
            }
        }).start();

        reciveChat();
    }

    public static void setNetworkCurMode(int model){
        Sdkv2.setNetworkCurMode(model);
    }


    //设置sdk 本地偏移
    public static void setLocalOffset(long offset, Map<String, Object> map) {
        localOffset = offset;
        Log.w("imchat init offset", localOffset + "");
        for (Map.Entry<String, Object> map1 : map.entrySet()) {
            Log.w("imchat init groupoffset", map1.getKey() + "---" + map1.getValue());
            groupOffsetMap.put(Long.valueOf(map1.getKey()), Long.valueOf((String) map1.getValue()));
        }
    }

    //同步 单聊偏移量
    public static void sync(long offset) {
        Sdkv2.imSync(offset);
    }

    //同步群聊偏移量
    public static void syncGroup(Map<String, Object> map) {
        if (null == map || map.size() == 0) {
            return;
        }
        for (Map.Entry<String, Object> map1 : map.entrySet()) {
            Log.w("imchat sync group", map1.getKey() + "---" + map1.getValue());
            Sdkv2.imSyncGroupData(Integer.valueOf(map1.getKey()), Long.valueOf((String) map1.getValue()));

        }
    }
    //同步群聊偏移量
    public static void syncGroup(long groupId, long groupOffset) {
        Sdkv2.imSyncGroupData(groupId, groupOffset);
    }

    /**
     * 接收事件状态值的线程
     */
    public static void reciveEvent() {
        try {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        long eventLength = Sdkv2.imReadCurImEventLen();
                        if (eventLength > 0) {
                            byte[] bytes = new byte[(int) eventLength];
                            Sdkv2.imReadCurImEventData(bytes);//读取
                            Intent intent = new Intent();
                            intent.setAction(BaseConstants.IM_DATA);
                            String json = new String(bytes);
                            Log.e("imevent", json);
                            ImEvent imEvent = new Gson().fromJson(json, ImEvent.class);
                            intent.putExtra(BaseConstants.IM_DATA_VALUE, imEvent);
                            mContext.sendBroadcast(intent);
                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 接收单聊的线程
     */
    public static void reciveChat() {
        try {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        Log.e("imchat", "im isAlive ");

                        long length = Sdkv2.imReadCurImChatMsgLen();
                        if (length > 0) {
                            byte[] bytes = new byte[(int) length];

                            Sdkv2.imReadCurImChatMsgData(bytes);//读取
                            try {
                                Sync.ImGroupSyncNotifyWithData ms = Sync.ImGroupSyncNotifyWithData.parseFrom(bytes);
                                Log.e("imchat person", "im offset = " + ms.getOffset() + "----" + ms.getContent());
                            } catch (InvalidProtocolBufferException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收群组消息的线程
     */
    public static void reciveGroupChat() {
        try {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        long length = Sdkv2.imReadCurImChatGroupMsgLen();
                        if (length > 0) {
                            byte[] bytes = new byte[(int) length];
                            Sdkv2.imReadCurImChatGroupMsgData(bytes);//读取
                            try {
                                Sync.ImGroupSendMsgSync ms = Sync.ImGroupSendMsgSync.parseFrom(bytes);

                                String content = bytesToString(ms.getContent(), "");
                                Log.e("imchat group", "im offset = " + ms.getOffset() + "----" +content);
                                Log.e("imchat", "im offset = " + ms.getOffset() + "----" + ms.getFromUID());
                                Log.e("imchat", "im offset = " + ms.getOffset() + "----" + ms.getToGroupid());
                                Log.e("imchat", "im offset = " + ms.getOffset() + "----" + ms.getTimestamp());
                                if (ms.getToGroupid()==0){//单聊消息,系统消息等
                                    ChatMsgEntity chatMsgEntity = new ChatMsgEntity();

                                    chatMsgEntity.setContent(content);
                                    chatMsgEntity.setFromUid(ms.getFromUID());
                                    chatMsgEntity.setToUID( ms.getToUID());
                                    chatMsgEntity.setMsgType(ms.getMsgType());
                                    chatMsgEntity.setOffset(ms.getOffset());
                                    chatMsgEntity.setTimeStep(ms.getTimestamp());
                                    chatMsgEntity.setMsgId(ms.getMsgid());
                                    Log.w("imchat", "ms.getOffset() = " + ms.getOffset() + "--localOffset--" + localOffset+"--- ---"+content+" "+chatMsgEntity);
                                    if (ms.getOffset() > localOffset) {

                                        Log.w("imchat","sendApp");
                                        Intent intent = new Intent();
                                        intent.setAction(BaseConstants.IM_DATA);
                                        intent.putExtra(BaseConstants.IM_DATA_VALUE, chatMsgEntity);
                                        mContext.sendBroadcast(intent);
                                        Sdkv2.imAckPeerOffset(ms.getOffset());
                                        localOffset = ms.getOffset();
                                    }else {
                                        //偏移小的消息 忽略
                                        Log.w("imchat","delete");
                                    }


                                }else {
                                    long preGroupOffset = 0l;
                                    if (groupOffsetMap.containsKey(ms.getToGroupid())) {
                                        preGroupOffset = groupOffsetMap.get(ms.getToGroupid());
                                    } else {
                                        groupOffsetMap.put(ms.getToGroupid(), ms.getOffset());
                                    }

                                    if (ms.getOffset() >= preGroupOffset) {
                                        Sdkv2.imAckGroupOffset(ms.getToGroupid(), ms.getOffset());
                                        ChatMsgEntity chatMsgEntity = new ChatMsgEntity();

                                        chatMsgEntity.setContent(content);
                                        chatMsgEntity.setFromUid(ms.getFromUID());
                                        chatMsgEntity.setMsgType(ms.getMsgType());
                                        chatMsgEntity.setOffset(ms.getOffset());
                                        chatMsgEntity.setTimeStep(ms.getTimestamp());
                                        chatMsgEntity.setMsgId(ms.getMsgid());
                                        chatMsgEntity.setGroupID(ms.getToGroupid());
                                        Log.e("imchat", "im offset = " + ms.getOffset() + "----" + content);
                                        Intent intent = new Intent();
                                        intent.setAction(BaseConstants.IM_DATA);
                                        intent.putExtra(BaseConstants.IM_DATA_VALUE, chatMsgEntity);
                                        groupOffsetMap.put(ms.getToGroupid(), ms.getOffset());//更新
                                        mContext.sendBroadcast(intent);
                                    }


                                }

                            } catch (InvalidProtocolBufferException e) {
                                e.printStackTrace();
                            } catch (CharacterCodingException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void loginOutIm() {
        Sdkv2.imLogout();
    }

    public static void IMSyncGroupData(int groupId, long localOffset) {
        Sdkv2.imSyncGroupData(groupId, localOffset);
    }

    /**
     * @param localMsgId 本地数据库id
     * @param toUid      接收方uid
     * @param msgType    消息类型
     * @param s          消息
     */
    public static void sendMsg(int localMsgId, long toUid, int msgType, String s) {
        //me 53
        if (toUid==13){
            toUid=700;
        }
        Log.w("imchat", "localMsgId = " + localMsgId + ",msgType = " + msgType + ", send content = " + s + ", other user toUid = " + toUid);
        Sdkv2.imSendPeeerMsg(localMsgId, toUid, msgType, s.getBytes().length, s.getBytes());
    }

    /**
     * 重发消息
     *
     * @param localMsgId 本地数据库id
     * @param toUid      接收方uid
     * @param msgType    消息类型
     * @param s          消息
     */
    public static void reSendMsg(int localMsgId, long toUid, int msgType, String s) {
        //me 53
        Log.w("imchat resend", "localMsgId = " + localMsgId + ",msgType = " + msgType + ", send content = " + s + ", other user toUid = " + toUid);
        Sdkv2.imSendPeeerMsg(localMsgId, toUid, msgType, s.getBytes().length, s.getBytes());
    }

    /**
     * @param localMsgId 本地数据库id
     * @param groupId    接收方uid
     * @param msgType    消息类型
     * @param s          消息
     */
    public static void sendGroupMsg(int localMsgId, long groupId, int msgType, String s) {
        Log.w("imchat", "localMsgId = " + localMsgId + ",msgType = " + msgType + ", send content = " + s + ", groupId = " + groupId);
        Sdkv2.imSendGroupMsg(localMsgId, groupId, msgType, s.getBytes().length, s.getBytes());
    }

    /**
     * @param localMsgId 本地数据库id
     * @param groupId    接收方uid
     * @param msgType    消息类型
     * @param s          消息
     */
    public static void reSendGroupMsg(int localMsgId, long groupId, int msgType, String s) {
        Log.w("imchat resend", "localMsgId = " + localMsgId + ",msgType = " + msgType + ", send content = " + s + ", groupId = " + groupId);
        Sdkv2.imSendGroupMsg(localMsgId, groupId, msgType, s.getBytes().length, s.getBytes());
    }

    public static String bytesToString(ByteString src, String charSet) throws CharacterCodingException {

        if (isEmpty(charSet)) {
            charSet = "UTF-8";
        }
        byte[] input = src.toByteArray();
        if (input.length == 0) {
            return null;
        }
        ByteBuffer buffer = ByteBuffer.allocate(input.length);
        buffer.put(input);
        buffer.flip();

        Charset charset = null;
        CharsetDecoder decoder = null;
        CharBuffer charBuffer = null;


        charset = Charset.forName(charSet);
        decoder = charset.newDecoder();
        charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
        return charBuffer.toString();

    }
}
